<template>
  <div id="usercontroll">
    <div id="usertop">
      <div style="display: inline-block;float: right">
        <el-button type="primary" @click="addUser">新增用户</el-button>
      </div>
      <div style="display: inline-block;float:left">
        <el-form>
          <el-form-item label="用户名">
            <el-input v-model.trim="userName" @input="query()"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style="display: inline-block;float:left">
        <el-form>
          <el-form-item label="手机号">
            <el-input v-model.trim="phonenumber" @input="query()"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div id="pagebox" style="clear: both">
      <el-container>
        <el-aside width="200px">
          <el-tree :data="treedata"  :props="defaultProps" @node-click="handleNodeClick" default-expand-all accordion />
        </el-aside>
        <el-main>
          <el-table :data="userlist" style="width: 100%">
            <el-table-column type="index" width="80" label="序号" />
            <el-table-column prop="userName" label="用户名" />
            <el-table-column prop="loginName" label="账号"  />
            <el-table-column prop="dept.deptName" label="部门"  />
            <el-table-column prop="phonenumber" label="手机" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" width="300">
              <template #default="scope" >
                <el-button size="small" type="primary" @click="userUpdate(scope.row)">编辑信息</el-button>
                <el-button size="small" type="warning" @click="userPassChange(scope.row)">修改密码</el-button>
                <el-button size="small" type="danger"  @click="userDelete(scope.row)">删除用户</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="float: right;padding-top: 1%">
            <el-pagination
                v-model:current-page="pageNum"
                v-model:page-size="pageSize"
                background layout="prev, pager, next"
                :total="total"
                @current-change="handleCurrentChange"/>
          </div>
        </el-main>

      </el-container>

    </div>
    <div id="passWordlog">
      <el-dialog v-model="dialogFormVisible" title="修改密码">
        <el-form :model="change">
          <el-form-item label="新密码" >
            <el-input v-model.trim="change.password"  show-password/>
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取消</el-button>
        <el-button type="primary" @click="confrimChange">
          确认
        </el-button>
      </span>
        </template>
      </el-dialog>
    </div>
    <div id="addUserLog">
      <el-dialog v-model="dialogAddUserFormVisible" title="新增用户" width="660">
        <el-form :model="newUser" >
          <el-form-item label="用户姓名" >
            <el-input v-model.trim="newUser.userName"/>
          </el-form-item>
          <el-form-item label="用户账号" >
            <el-input v-model.trim="newUser.loginName"/>
          </el-form-item>
          <el-form-item label="手机号码" >
            <el-input v-model.trim="newUser.phonenumber" oninput="value=value.replace(/[^0-9.]/g,'')"/>
          </el-form-item>
          <el-form-item label="登陆密码" >
            <el-input v-model.trim="newUser.password"  show-password/>
          </el-form-item>
          <el-form-item label="用户性别" >
            <el-select v-model="newUser.sex" placeholder="请选择">
              <el-option label="男" :value="0"/>
              <el-option label="女" :value="1"/>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="用户邮箱" >-->
<!--            <el-input v-model="newUser.email"/>-->
<!--          </el-form-item>-->
          <el-form-item label="用户岗位" >
            <el-checkbox-group v-model="newUser.postIds">
              <el-checkbox v-for="item in posts" :label="item.postId"  :key="item.postId">{{item.postName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="归属部门" >
            <el-select v-model="newUser.deptId" placeholder="请选择">
              <el-option v-for="item in depts" :label="item.deptName" :value="item.deptId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="用户角色" >
            <el-checkbox-group v-model="newUser.roleIds" @change="setMealSelect2">
              <el-checkbox v-for="item in roles" :label="item.roleId"  :key="item.roleId">{{item.roleName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogAddUserFormVisible=false">取消</el-button>
        <el-button type="primary" @click="confrimAddUser">
          确认
        </el-button>
      </span>
        </template>
      </el-dialog>
    </div>
    <div id="updateUserLog">
      <el-dialog v-model="dialogUpdataUserFormVisible" title="修改用户" width="660">
        <el-form :model="upDataUser" >
          <el-form-item label="用户姓名" >
            <el-input v-model.trim="upDataUser.userName"/>
          </el-form-item>
          <el-form-item label="用户账号" >
            <el-input v-model.trim="upDataUser.loginName"/>
          </el-form-item>
          <el-form-item label="手机号码" >
            <el-input v-model.trim="upDataUser.phonenumber" oninput="value=value.replace(/[^0-9.]/g,'')"/>
          </el-form-item>
          <el-form-item label="用户性别" >
            <el-select v-model="upDataUser.sex" placeholder="请选择">
              <el-option label="男" value="0"/>
              <el-option label="女" value="1"/>
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="用户邮箱" >-->
          <!--            <el-input v-model="newUser.email"/>-->
          <!--          </el-form-item>-->
          <el-form-item label="用户岗位" >
            <el-checkbox-group v-model="upDataUser.postIds">
              <el-checkbox v-for="(item,index) in posts" :label="item.postId"  :key="index">{{item.postName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="归属部门" >
            <el-select v-model="upDataUser.deptId" placeholder="请选择">
              <el-option v-for="item in depts" :label="item.deptName" :value="item.deptId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="用户角色" >
            <el-checkbox-group v-model="upDataUser.roleIds"  @change="setMealSelect">
              <el-checkbox v-for="item in roles" :label="item.roleId"  :key="item.roleId">{{item.roleName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogUpdataUserFormVisible=false">取消</el-button>
        <el-button type="primary" @click="confrimUpdataUser">确认</el-button>
      </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup lang="ts">

import {
  addUserVue,
  deleteUser,
  editUserVue,
  getDeptAndRole,
  resetPwdVue,
  treeData,
  updataUserVue,
  userList, userListTree
} from "../../api/system";
import {onMounted, ref,reactive} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus'
import {useUsersStore} from "../../store/userInfo.ts";
const store = useUsersStore();
const { name, role, token } = store;
let treedata = ref<any>([])
let userlist = ref<any>([])
let dialogFormVisible = ref<any>(false)
let dialogAddUserFormVisible = ref<any>(false)
let dialogUpdataUserFormVisible = ref<any>(false)
let posts = ref<any>([]);
let depts  = ref<any>([]);
let roles  = ref<any>([]);
let pageNum = ref<number>(1);
let pageSize = ref<number>(10);
let nodeId  = ref<string>('');
let total = ref<number>(0)
let userName = ref<string>('');
let phonenumber = ref<string>('');
// let userRole = ref<any>( useUsersStore());
let  change:any = reactive({
  userId:'',
  loginName:'',
  password:'',
});
let newUser:any = reactive({
  deptId:'',
  loginName:'',
  userName:'',
  email:'',
  phonenumber:'',
  sex:'',
  password:'aa123456',
  status:'0',
  remark:'',
  postIds:[],
  roleIds:[],
})
let upDataUser = ref({})
onMounted(async () => {
  await query();
})
const defaultProps = {
  children: 'children',
  label: 'name',
}
const query = async () => {
  let res1:any = await treeData(null);
  let res2:any = await userList({pageNum:pageNum.value,pageSize:pageSize.value,userName:userName.value,phonenumber:phonenumber.value});
  let res3:any = await getDeptAndRole(null);
  treedata.value = res1.data;
  userlist.value  = res2.data.list;
  posts.value = res3.data.posts;
  roles.value = res3.data.roles;
  depts.value = res3.data.depts;
  total.value = res2.data.total
}

const handleNodeClick = async (node) => {
  nodeId.value = node.id
  let res2 = await userListTree({
    id:node.id,
    pageNum:pageNum.value,
    pageSize:pageSize.value
  });
  userlist.value  = res2.data.list
  total.value = res2.data.total
}
const userUpdate = async (row) => {
  let res = await updataUserVue({userId: row.userId});
  upDataUser.value=res.data.user[0];
  roles.value = res.data.roles;
  posts.value = res.data.posts;
  dialogUpdataUserFormVisible.value = true;
}
const userPassChange = (row) => {
  change = reactive({
    userId:'',
    loginName:'',
    password:'',
  });
  change.userId =row.userId;
  change.loginName =row.loginName;
  dialogFormVisible.value=true;
}
const confrimChange = async () => {
  const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/;
  const { password, userId, loginName } = change;
  if (password.length === 0) {
    ElMessage.error("新密码不能为空");
    return;
  }
  if (!reg.test(password)) {
    ElMessage.error("密码不符合规范：6-12字符，包括字母和数字");
    return;
  }
    const res = await resetPwdVue({ userId, password, loginName });
    if (res.code == 200) {
      ElMessage.success("密码修改成功");
      dialogFormVisible.value = false;
    }
}
const userDelete = (row) => {
  ElMessageBox.confirm('确认要删除该用户吗?')
      .then(async () => {
        let res = await deleteUser({ids: row.userId});
        if (res.code ==200){
          ElMessage.success(res.msg)
          await query();
        }else{
          ElMessage.error(res.msg)
        }
      })
      .catch(() => {
        // catch error
      })
}
const addUser = () => {
  dialogAddUserFormVisible.value = true;

}
const confrimAddUser = async () => {
  let res = await addUserVue({
    deptId:newUser.deptId,
    loginName:newUser.loginName,
    userName:newUser.userName,
    email:newUser.email,
    phonenumber:newUser.phonenumber,
    sex:newUser.sex,
    password:newUser.password,
    status:newUser.status,
    remark:newUser.remark,
    postIds:newUser.postIds,
    roleIds:newUser.roleIds,
  });
  if (res.code==200){
    ElMessage.success(res.msg)
    await query();
    dialogAddUserFormVisible.value=false;
  }else{
    ElMessage.error(res.msg)
  }
}
const confrimUpdataUser = async () => {
  let res = await editUserVue({
    deptId: upDataUser.value.deptId,
    loginName: upDataUser.value.loginName,
    userName: upDataUser.value.userName,
    email: upDataUser.value.email,
    phonenumber: upDataUser.value.phonenumber,
    sex: upDataUser.value.sex,
    password: upDataUser.value.password,
    status: upDataUser.value.status,
    remark: upDataUser.value.remark,
    postIds: upDataUser.value.postIds,
    roleIds: upDataUser.value.roleIds,
    userId: upDataUser.value.userId,
  });
  if (res.code == 200) {
    ElMessage.success(res.msg)
    await query();
    dialogUpdataUserFormVisible.value = false;
  } else {
    ElMessage.error(res.msg)
  }

}
const setMealSelect =async  () => {
  upDataUser.value.roleIds = upDataUser.value.roleIds.slice(-1)
}
const setMealSelect2 =async  () => {
  newUser.roleIds = newUser.roleIds.slice(-1)
}
const handleCurrentChange = async (val: number) => {
  pageNum.value = val;
  if (nodeId.value == ""){
    await query();
  }else {
    let res2 = await userListTree({
      id:nodeId.value,
      pageNum:pageNum.value,
      pageSize:pageSize.value
    });
    userlist.value  = res2.data.list
    total.value = res2.data.total
  }
}
</script>
<style scoped>

</style>
